package com.micro.edu.filter;


import io.netty.util.concurrent.DefaultThreadFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@RefreshScope
public class RegisterIpLimitFilter implements GlobalFilter, Ordered, InitializingBean {


    private final static ConcurrentHashMap<String, AtomicInteger> requestCountMap = new ConcurrentHashMap<>();
    private final static ConcurrentHashMap<String, Long> requestTimeMap = new ConcurrentHashMap<>();

    @Value("${register.limitCount}")
    private int limitCount;//请求数
    @Value("${register.limitTime}")
    private int limitTime; //分钟数

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        if (!path.contains("/user/register")) {
            return chain.filter(exchange);
        }
        ServerHttpResponse response = exchange.getResponse();
        InetSocketAddress remoteAddress = request.getRemoteAddress();
        String hostString = remoteAddress.getHostString();
        AtomicInteger integer = requestCountMap.get(hostString);
        int count = 0;
        if (integer == null) {
            count = 1;
            integer = new AtomicInteger(count);
        } else {
            count = integer.incrementAndGet();
        }
        requestCountMap.put(hostString, integer);
        if (count < limitCount) {
            return chain.filter(exchange);
        }
        DataBuffer wrap = response.bufferFactory().wrap("您频繁进⾏注册，请求已被拒绝".getBytes());
        response.setStatusCode(HttpStatus.FORBIDDEN);
        return response.writeWith(Mono.just(wrap));
    }

    @Override
    public int getOrder() {
        return 0;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10, new DefaultThreadFactory("scheduled-task-pool"));
        executor.scheduleWithFixedDelay(() -> {
            for (Map.Entry<String, Long> entry : requestTimeMap.entrySet()) {
                Long requestTime = entry.getValue();
                String ip = entry.getKey();
                if (((System.currentTimeMillis() - requestTime) / (1000 * 60)) > limitTime) {
                    requestTimeMap.remove(ip);
                    requestCountMap.remove(ip);
                }
            }
        }, limitTime, limitTime, TimeUnit.MINUTES);
    }
}
